package com.weacar.adapter;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.SparseArray;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.bumptech.glide.Glide;
import com.example.zhouwei.library.CustomPopWindow;
import com.google.gson.Gson;
import com.kongzue.dialog.interfaces.OnDialogButtonClickListener;
import com.kongzue.dialog.util.BaseDialog;
import com.kongzue.dialog.v3.MessageDialog;
import com.weacar.R;
import com.weacar.activity.CarDetailActivity;
import com.weacar.activity.MainActivity;
import com.weacar.bean.AuctionBean;
import com.weacar.bean.BaseBean;
import com.weacar.bean.CarBean;
import com.weacar.config.Constans;
import com.weacar.fragment.MyPriceFragment;
import com.weacar.utils.DesUtil;
import com.weacar.utils.NetWorkUtil;
import com.weacar.utils.PriceUtil;
import com.weacar.utils.TimeUtil;
import com.weacar.utils.ToastUtil;
import com.weacar.utils.UserInfoUtil;

import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.math.BigDecimal;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class TimeCountDownAuctionAdapter extends BaseAdapter {

    private List<AuctionBean.MsgBean> mDatas;
    private Context mContext;
    private MainActivity mainActivity;
    private MyPriceFragment myPriceFragment;

    private LayoutInflater mInflater;

    //用于退出 Activity,避免 Countdown，造成资源浪费。
    private SparseArray<CountDownTimer> countDownCounters;


    public TimeCountDownAuctionAdapter(List<AuctionBean.MsgBean> mDatas, Context mContext, MainActivity mainActivity, MyPriceFragment myPriceFragment) {
        this.mDatas = mDatas;
        this.mContext = mContext;
        this.mainActivity = mainActivity;
        this.myPriceFragment = myPriceFragment;
        this.countDownCounters = new SparseArray<>();
        mInflater = LayoutInflater.from(mContext);
    }

    @Override
    public int getCount() {
        return mDatas.size();
    }

    @Override
    public Object getItem(int i) {
        return mDatas.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View convertView, ViewGroup viewGroup) {
        ViewHolder holder = null;
        final AuctionBean.MsgBean msgBean = mDatas.get(i);
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.item_lv_auction_doing, viewGroup, false);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }


        // 倒计时相关
        if (msgBean.getEnd_time() != null && !msgBean.getEnd_time().equals("")) {
            holder.tv_auction_time.setVisibility(View.VISIBLE);
            CountDownTimer countDownTimer = countDownCounters.get(holder.tv_auction_time.hashCode());
            if (countDownTimer != null) {
                //将复用的倒计时清除
                countDownTimer.cancel();
            }
            final ViewHolder finalHolder = holder;
            long timer = 0;
            timer = TimeUtil.dateDiff(msgBean.getEnd_time());
            if (timer > 0) {
                countDownTimer = new CountDownTimer(timer, 1000) {
                    @Override
                    public void onTick(long l) {
                        long time = l / 1000;
                        finalHolder.tv_auction_time.setText(TimeUtil.formatLongToTimerStrNoDesc(time));
                    }

                    @Override
                    public void onFinish() {
                        finalHolder.tv_auction_time.setText("时间结束");
                    }
                }.start();
                countDownCounters.put(holder.tv_auction_time.hashCode(), countDownTimer);
            } else {
                finalHolder.tv_auction_time.setText("时间结束");
            }
        } else {
            holder.tv_auction_time.setVisibility(View.GONE);
        }

        holder.rl_head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mContext, CarDetailActivity.class);
                intent.putExtra("web_url", msgBean.getWeb_url());
                intent.putExtra("car_id", msgBean.getCar_id());
                intent.putExtra("token", UserInfoUtil.getToken(mContext));
                intent.putExtra("auction_type", 1);
                mContext.startActivity(intent);
            }
        });

        final ViewHolder finalHolder1 = holder;
        holder.tv_change_price.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPricePop(finalHolder1.rl_main, msgBean.getCar_id());
            }
        });


        holder.tv_title.setText(msgBean.getName());
        holder.tv_condition.setText(msgBean.getLicensing_date() + "|" + msgBean.getCapacity_name() + "|" + String.format("%.2f", msgBean.getDisplayed_mileage()) + "万公里");
        if (msgBean.getOffer_price().contains(".")) {
            holder.tv_price.setText(PriceUtil.getPriceByWan(Integer.parseInt(msgBean.getOffer_price().substring(0, msgBean.getOffer_price().indexOf(".")))) + "万");
        } else {
            holder.tv_price.setText(PriceUtil.getPriceByWan(Integer.parseInt(msgBean.getOffer_price())) + "万");
        }
        return convertView;
    }

    static class ViewHolder {

        @BindView(R.id.tv_title)
        TextView tv_title;
        @BindView(R.id.tv_condition)
        TextView tv_condition;
        @BindView(R.id.tv_price)
        TextView tv_price;
        @BindView(R.id.tv_auction_time)
        TextView tv_auction_time;
        @BindView(R.id.tv_change_price)
        TextView tv_change_price;
        @BindView(R.id.rl_head)
        RelativeLayout rl_head;
        @BindView(R.id.rl_main)
        RelativeLayout rl_main;

        public ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }

    /**
     * 显示popwindow
     *
     * @param rl_main
     */
    public void showPricePop(RelativeLayout rl_main, final int car_id) {
        Resources resources = mContext.getResources();

        DisplayMetrics displayMetrics = resources.getDisplayMetrics();

        int widthPixels = (int) (displayMetrics.widthPixels * 0.8);//当前屏幕宽

        int heightPixels = (int) (displayMetrics.heightPixels * 0.5);//当前屏幕高


        View contentView = LayoutInflater.from(mContext).inflate(R.layout.pop_show_my_price, null);
        TextView tv_cancel = contentView.findViewById(R.id.tv_cancel);
        TextView tv_confirm = contentView.findViewById(R.id.tv_confirm);
        final TextView tv_ob_price = contentView.findViewById(R.id.tv_ob_price);
        final EditText et_price = contentView.findViewById(R.id.et_price);
        ImageView iv_clean = contentView.findViewById(R.id.iv_clean);

        // 监听用户输入
        et_price.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {

                if (editable.toString().equals("")) {
                    tv_ob_price.setText("");
                } else {
                    double d = Double.parseDouble(editable.toString());
                    tv_ob_price.setText(PriceUtil.digitUppercase(d));
                }

            }
        });


        final CustomPopWindow customPopWindow = new CustomPopWindow.PopupWindowBuilder(mContext)
                .setView(contentView)
                .enableBackgroundDark(true) //弹出popWindow时，背景是否变暗
                .setBgDarkAlpha(0.7f) // 控制亮度
                .size(widthPixels, heightPixels)//显示大小
                .create()
                .showAtLocation(rl_main, Gravity.CENTER, 0, 0);

        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                customPopWindow.dissmiss();
            }
        });

        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (et_price.getText().toString().equals("")) {
                    ToastUtil.showShort(mContext, "请输入正确格式的价格");
                    return;
                }

                final int price = Integer.parseInt(et_price.getText().toString());

                if (price == 0) {
                    ToastUtil.showShort(mContext, "请输入正确格式的价格");
                    return;
                }

                if (price % 100 == 0) {
                    String format_price = PriceUtil.getCommaFormat(BigDecimal.valueOf(price));
                    MessageDialog.show(mainActivity, "提示:竞拍后价格不能取消", "您输入的价格是:" + format_price + "元" + "(" + PriceUtil.digitUppercase(price) + ")", "确定出价", "取消").setOnOkButtonClickListener(new OnDialogButtonClickListener() {
                        @Override
                        public boolean onClick(BaseDialog baseDialog, View v) {
                            // 提交出价到服务器
                            commitPriceToServer(price, car_id);
                            return false;
                        }
                    });
                    customPopWindow.dissmiss();
                } else {
                    ToastUtil.showShort(mContext, "请输入正确格式的价格");
                }
            }
        });
        iv_clean.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                et_price.setText("");
            }
        });
    }


    /**
     * 提交竞拍价格
     */
    public void commitPriceToServer(final int price, int car_id) {
        if (!NetWorkUtil.isNetworkAvailable(mainActivity)) {
            ToastUtil.showShort(mainActivity, "当前网络不可用");
            return;
        }
        try {
            mainActivity.showLoading("提交出价到服务器中...");
            RequestParams params = new RequestParams(Constans.URL_HEADER + Constans.commit_price);
            params.setCacheMaxAge(0);
            JSONObject js_request = new JSONObject();
            js_request.put("token", UserInfoUtil.getToken(mainActivity));
            js_request.put("id", car_id);
            js_request.put("price", price);
            params.setAsJsonContent(true);
            params.setBodyContent(DesUtil.encrypt(js_request.toString()));
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    mainActivity.closeLoading();
                    LogUtils.d("result = " + result);
                    Gson gson = new Gson();
                    BaseBean baseBean = gson.fromJson(result, BaseBean.class);
                    if (baseBean != null) {
                        try {
                            com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(DesUtil.decrypt(baseBean.getData()));
                            String msg = jsonObject.get("msg").toString();
                            if (msg.equals("出价成功")) {
                                myPriceFragment.refreshDoingData();
                            }
                            ToastUtil.showShort(mainActivity, msg);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    mainActivity.closeLoading();
                }

                @Override
                public void onCancelled(CancelledException cex) {
                    mainActivity.closeLoading();
                }

                @Override
                public void onFinished() {
                    mainActivity.closeLoading();
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void cancelAllTimers() {
        if (countDownCounters == null) {
            return;
        }
        for (int i = 0, length = countDownCounters.size(); i < length; i++) {
            CountDownTimer cdt = countDownCounters.get(countDownCounters.keyAt(i));
            if (cdt != null) {
                cdt.cancel();
            }
        }
    }
}
